package com.gf.snoopy.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gf.snoopy.dto.ProjectDto;
import com.gf.snoopy.platform.exception.PokeErrorCode;
import com.gf.snoopy.platform.exception.PokeException;
import com.gf.snoopy.platform.result.PokeResult;
import com.gf.snoopy.service.ProjectService;
import com.gf.snoopy.util.AoDataPage;
import com.gf.snoopy.util.ConvertUtil;
import com.gf.snoopy.util.SnoopyUtil;
import com.gf.snoopy.util.page.Page;
import com.gf.snoopy.util.page.PagedList;

import javax.annotation.Resource;

@Controller
@RequestMapping("/")
public class ProjectController {
	
	private Logger logger = Logger.getLogger(ProjectController.class);
	
	@Resource
	private ProjectService projectService;
	
	@RequestMapping("/")
	public ModelAndView index(){
		return new ModelAndView("index");
	}
	
	/**
	 * 分页获取项目详情
	 * @param voteId
	 * @param aoData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/project/showPage")
	@ResponseBody	
	public String getProjectPage(String aoData) throws Exception{
		if(aoData==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		AoDataPage aoDataPage = SnoopyUtil.parseAoData(aoData);
		Page page = new Page();
		page.setOffset(aoDataPage.offset);
		page.setPageSize(aoDataPage.pageSize);
		ProjectDto dto = new ProjectDto();
		dto.setShortName(aoDataPage.search);
		PagedList<ProjectDto> projectDtos = projectService.getProjectPage(dto, page);
		return PokeResult.getPokeResultSuccess(SnoopyUtil.constructPageResult(projectDtos));
	}
	
	@RequestMapping("/project/save")
	@ResponseBody
	public String saveOrUpateProject(@RequestBody String jsonPorject) throws Exception{
		if(jsonPorject==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		ProjectDto dto = ConvertUtil.convertJsonToBean(jsonPorject,ProjectDto.class);
		if(dto.getId()==null){
			projectService.save(dto);
		}else{
			projectService.update(dto);
		}
		return PokeResult.getPokeResultSuccess(SnoopyUtil.SUCCESS);
	}
	
	/**
	 * 根据Id查找结果
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/project/find")
	@ResponseBody
	public String findById(Integer id) throws Exception{
		ProjectDto result = projectService.findById(id);
		return PokeResult.getPokeResultSuccess(result);
	}

	/**
	 * 根据Id删除结果
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/project/delete")
	@ResponseBody
	public String deleteById(Integer id) throws Exception{
		projectService.deleteById(id);
		return PokeResult.getPokeResultSuccess(SnoopyUtil.SUCCESS);
	}
	

}
